package com.cqhz.quwan.ui.mine

import android.Manifest
import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.UserInfoBean
import com.cqhz.quwan.mvp.mine.UserInfoContract
import com.cqhz.quwan.mvp.mine.UserInfoPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.util.GlideImageLoader
import com.cqhz.quwan.util.UploadUtil
import com.cqhz.quwan.util.isContainChinese
import com.cqhz.quwan.util.setLoadImage
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yancy.gallerypick.config.GalleryConfig
import com.yancy.gallerypick.config.GalleryPick
import com.yancy.gallerypick.inter.IHandlerCallBack
import kotlinx.android.synthetic.main.activity_infomation.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject


/**
 * 个人信息
 * Created by Guojing on 2018/9/6.
 */
class InformationActivity : GoBackActivity(), UserInfoContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var userInfoPresenter: UserInfoPresenter
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null
    private var headAddress: String = ""
    private var isEdit: Boolean = false
    private var rxPermissions: RxPermissions? = null

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_infomation
    }

    override fun beforeInitView() {
        super.beforeInitView()
        rxPermissions = RxPermissions(this)
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean
        // 用户头像
        setHeadUrl(userInfoBean.headAddress)
        val nickname = userInfoBean.nickName ?: "未填写"
        val name = userInfoBean.realName ?: "未实名"
        val sex = when {
            userInfoBean.sex == "1" -> "女"
            userInfoBean.sex == "2" -> "男"
            else -> "未知"
        }
        val age = userInfoBean.age ?: "未实名"
        val mobile = userInfoBean.mobile ?: "未知"
        val city = userInfoBean.city ?: "未知"
        val address = if (userInfoBean.addressId == null) "未设置" else "已设置"

        et_nickname.setText(nickname)
        tv_name.text = name
        tv_sex.text = sex
        tv_age.text = age
        tv_phone.text = mobile
        tv_area.text = city
        tv_address_enable.text = address

        action_goto_address.setOnClickListener { startActivity(Intent(this, AddressActivity::class.java)) }
    }

    override fun titleBarText(): String? {
        return "个人信息"
    }

    override fun initView() {
        userInfoPresenter.attachView(this)
        loginBean = APP.get()!!.loginInfo
        if (loginBean != null) {
            showLoading("正在加载数据...")
            userInfoPresenter.getUserInfo(loginBean!!.userId!!)
        }

        setTitleBarRightText("修改", ({
            isEdit = true
            setEditStyle()
        }))

        // 头像
        action_update_avatar.setOnClickListener {
            if (!isEdit) return@setOnClickListener
            // 调用拍照模块
            rxPermissions!!.requestEachCombined(Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe { permission ->
                        if (permission.granted) {
                            selectImages()
                        }
                    }
        }

        action_save.setOnClickListener {
            if (!isEdit) return@setOnClickListener
            val nickname = et_nickname.text.toString().trim()
            userInfoPresenter.updateUserInfo(loginBean!!.userId!!, headAddress, nickname)// 保存
        }
    }

    /**
     *  设置编辑样式
     */
    private fun setEditStyle() {
        setTitleBarRightText(if (isEdit) "" else "修改") {}
        et_nickname.isCursorVisible = isEdit
        et_nickname.isFocusable = isEdit
        et_nickname.isFocusableInTouchMode = isEdit
        action_save.visibility = if (isEdit) View.VISIBLE else View.GONE
    }

    override fun setHeadUrl(url: String?) {
        headAddress = if (StringUtils.isEmpty(url)) "http://h5.zhanguo.fun/td/img/img_tx.png" else url!!// 暂时使用
        iv_avatar.isEnabled = false
        iv_avatar.setLoadImage(this, headAddress, R.mipmap.iv_default_head)// 用户头像
    }

    /**
     * 选择上传的图片
     */
    private fun selectImages() {
        val galleryConfig = GalleryConfig.Builder()
                .imageLoader(GlideImageLoader())// ImageLoader 加载框架（必填）
                .iHandlerCallBack(object : IHandlerCallBack {
                    override fun onStart() {

                    }

                    override fun onSuccess(files: List<String>) {
                        UploadUtil.uploadImages(files, object : UploadUtil.CallResult<String> {
                            override fun onResponse(data: String) {
                                if (data.isContainChinese()) {
                                    showToast(data)
                                } else {
                                    setHeadUrl(data)
                                }
                            }

                            override fun onFailure(data: String) {
                                showToast("保存失败，请重试")
                            }
                        })
                    }

                    override fun onCancel() {

                    }

                    override fun onFinish() {

                    }

                    override fun onError() {

                    }
                })// 监听接口（必填）
                .multiSelect(true, 1)
                .provider(KeyContract.FILE_PROVIDER)// provider (必填)
                .isShowCamera(true)// 是否显示相机按钮  默认：false
                .filePath(KeyContract.FILE_PATH)// 图片存放路径
                .build()
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this)// 开启图片选择器
    }

    override fun refresh() {
        showToast("保存成功")
        isEdit = false
        setEditStyle()
    }

    override fun onDestroy() {
        userInfoPresenter.detachView()
        super.onDestroy()
    }
}